﻿using System;
using System.Collections.Generic;
using Mbs;

namespace EventBroker.Module
{
    public interface ICustomerEditView : IView
    {
        string CustomerId { get; set; }
        void CustomerIdFocus();
    }

    public interface IGlobalCustomerView:ICustomerEditView{
    }

    public interface ICustomerListView:ICustomerEditView
    {
        void DisplayGlobalCustomers(List<string> customers);
        void DisplayLocalCustomers(List<string> customers);
        void Display();
    }

    public interface IProgressView : IView
    {
        int ProgressValue { set; }
        void Show();
    }

    public interface IGlobalCustomerPresenter : IPresenter<IGlobalCustomerView> { }

    public interface ICustomerListPresenter : IPresenter<ICustomerListView>
    {
        List<string> LocalCustomers { get; set; }
        List<string> GlobalCustomers { get; set; }
        void Navigate();
    }

    public class GlobalCustomerPresenter : Presenter<IGlobalCustomerView>, IGlobalCustomerPresenter
    {
        public List<string> Customers { get; private set; }

        public GlobalCustomerPresenter()
        {
            Customers = new List<string>();
        }

        public override IEnumerator<IDisposable> Subscribe()
        {
            yield return CommandNames.AddCustomer.Subscribe<EventArgs>((s, e) => AddCustomer());
            yield return CommandNames.NewCustomerList.Subscribe<EventArgs>((s, e) => ShowCustomerList());
        }

        private object syncRoot = new object();

        private void AddCustomer()
        {
            if (!string.IsNullOrEmpty(View.CustomerId))
            {
                lock (syncRoot)
                {
                    Customers.Add(View.CustomerId);
                }
                CommandNames.GlobalCustomerAdded.Publish(this.
                    Customers);
            }
            View.CustomerIdFocus();
        }


        private void ShowCustomerList()
        {
            using (var customerListPresenter = ServiceLocator.Current.Get<ICustomerListPresenter>())
            {
                customerListPresenter.GlobalCustomers = Customers;
                customerListPresenter.Navigate();
            }
        }
    }
}
